package cat.joronya.supermanager.privateleague;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.drawer.EmptyMessageFragment;
import cat.joronya.supermanager.widget.CheckableRelativeLayout;

/**
 * Fragment per llistat les lligues privades de l'usuari.
 * @author pol
 */
public class PrivateLeagueListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
	// pel Log
	private static final String TAG = "supermanager";
	
	// loader id
	private static final int LIST_LOADER = 0x01;
	
	// the adapter
	private PrivateLeagueAdapter adapter;
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.PrivateLeague._ID, 			// 0
            Supermanager.PrivateLeague.ID_PRIV, 		// 1
            Supermanager.PrivateLeague.NAME, 			// 2
            Supermanager.PrivateLeague.NUMBER_OF_TEAMS, // 3
            Supermanager.PrivateLeague.MODIFIED_DATE 	// 4
    };
    
    boolean mDualPane;
    int mCurCheckPosition = 0;
    long mCurCheckId = 0;
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
    	// If not container present, don't generate the view so this fragment
    	// is not visible. Doing so, may cause problems with FragmentManager on
    	// recreation of the activity when orientation changes occur and different
    	// layout is loaded with id's no present anymore on it.
    	if( container == null )
    	{
    		return null;
    	}
    	
    	View view = inflater.inflate(R.layout.private_league_list, null);
    	
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getActivity().getIntent();
        Uri plUri = getActivity().getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeague.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeague.CONTENT_URI);
        }
	
        // per si venim de canvi d'orientacio, agafem el id de la pl a mostrar al inciar
        mCurCheckId = getActivity().getIntent().getLongExtra("cat.joronya.supermanager.privateleague.id",0);
        mCurCheckPosition = getActivity().getIntent().getIntExtra("cat.joronya.supermanager.privateleague.position", 0);
        
        // Used to map notes entries from the database to views
        adapter = new PrivateLeagueAdapter(getActivity().getApplicationContext(), null);
        setListAdapter(adapter);
        
        // initialize the loader
        getLoaderManager().initLoader(LIST_LOADER, null, this);
        
		// avisem q el fragment te menu pq es cridi
        //setHasOptionsMenu(true);
        
        return view;
	}
    
    @Override
	public void onViewCreated(View view, Bundle savedInstanceState) 
    {
		super.onViewCreated(view, savedInstanceState);
		
		 // Check to see if we have a frame in which to embed the details
        // fragment directly in the containing UI.
        View detailsFrame = getActivity().findViewById(R.id.detail_fragment);
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        if(savedInstanceState != null) 
        {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            mCurCheckId = savedInstanceState.getLong("curId", 0);
        }

        if(mDualPane) 
        {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition, mCurCheckId);
        }
	}

    class PrivateLeagueAdapter extends CursorAdapter implements CheckableRelativeLayout.OnCheckedChangeListener
	{
    	public PrivateLeagueAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			String name = cursor.getString(2);
			TextView nameView = (TextView)view.findViewById(R.id.private_league_list_row_name);
			nameView.setText(name);
			
			String numberOfTeams = cursor.getString(3);
			TextView numberOfTeamsView = (TextView)view.findViewById(R.id.private_league_list_row_members);
			numberOfTeamsView.setText(numberOfTeams);
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			CheckableRelativeLayout row = (CheckableRelativeLayout)inflater.inflate(R.layout.private_league_list_row, parent, false);
			row.setOnCheckedChangeListener(this);
			return row;
		}

		public void onCheckedChanged(CheckableRelativeLayout layout,
				boolean isChecked) {
			layout.setBackgroundColor((isChecked)? 
					getResources().getColor(R.color.blue):getResources().getColor(R.color.white));
		}
    }

	@Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }
    
    /**
	 * Al clicar una lliga privada anem al detall.
	 */
    @Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		Log.d(TAG,"veient detall de lliga privada amb _id: "+id);
		showDetails(position,id);
	}
    
    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index, long id) 
    {
        mCurCheckPosition = index;
        mCurCheckId = id;

        if(mDualPane) 
        {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            Fragment empty = getFragmentManager().findFragmentById(R.id.detail_fragment);
            
            // not initialized and id == 0, set empty fragment
            if( empty == null && id == 0 )
            {
            	// show empty fragment with message
            	EmptyMessageFragment emptyMessageFragment = EmptyMessageFragment.newInstance(getString(R.string.private_league_list_empty_fragment_message));
            	FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.detail_fragment, emptyMessageFragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
            // first selection, change empty message fragment with detail
            else if( empty instanceof EmptyMessageFragment )
            {
            	// Make new fragment to show this selection.
            	PrivateLeagueDetailFragment detail = PrivateLeagueDetailFragment.newInstance(id);
            	
            	// Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
               	FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.detail_fragment, detail);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
            // otherwise, change detail with other detail
            else
            {
            	PrivateLeagueDetailFragment detail = (PrivateLeagueDetailFragment)
                    getFragmentManager().findFragmentById(R.id.detail_fragment);
            	
            	if( detail == null )
            	{
            		detail = PrivateLeagueDetailFragment.newInstance(id);

            		// Execute a transaction, replacing any existing fragment
            		// with this one inside the frame.
            		FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.detail_fragment, detail);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
            	}
            	else if( detail.getShownIndex() != id) 
            	{
            		// Make new fragment to show this selection.
            		detail = PrivateLeagueDetailFragment.newInstance(id);

            		// Execute a transaction, replacing any existing fragment
            		// with this one inside the frame.
            		FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.detail_fragment, detail);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
            	}
            }
        } 
        else 
        {
        	// Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), PrivateLeagueDetailActivity.class);
            intent.putExtra("cat.joronya.supermanager.privateleague.id", id);
            intent.putExtra("cat.joronya.supermanager.privateleague.position", mCurCheckPosition);
            startActivity(intent);
        }
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    {
        inflater.inflate(R.menu.private_league_list, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
	public void onPrepareOptionsMenu(Menu menu) 
    {
		for( int i=0;  i<menu.size(); i++) 
		{
			MenuItem menuItem = menu.getItem(i);
			boolean isEnabled = false;
			switch(menuItem.getItemId())
			{
				case R.id.create:
					isEnabled = false;
					break;
				default:
				case R.id.join:
					isEnabled = false;
					break;
			}
			menuItem.setEnabled(isEnabled);
		}
		super.onPrepareOptionsMenu(menu);
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.join:
        		startActivity(new Intent(getActivity(),SearchPrivateLeagueActivity.class)
    				.setData(Supermanager.PrivateLeague.CONTENT_URI));
				return true;
        	case R.id.create:
        		startActivity(new Intent(getActivity(),CreatePrivateLeagueActivity.class)
					.setData(Supermanager.PrivateLeague.CONTENT_URI));
			return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }

	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) 
	{
		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				Supermanager.PrivateLeague.CONTENT_URI, 
				PROJECTION, 
				null, 
				null, 
				Supermanager.PrivateLeague.DEFAULT_SORT_ORDER);
	    return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
	{
		adapter.swapCursor(cursor);
	}

	public void onLoaderReset(Loader<Cursor> loader) 
	{
		adapter.swapCursor(null);
	}
    
    
}
